package com.tduck.cloud.common.helper;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
import com.tduck.cloud.common.util.SpringContextUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.core.env.Environment;


/**
 * 数据库助手
 *
 * @author tduck
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DataBaseHelper {

    private static String dataSourceUrl;


    /**
     * 获取当前数据库链接url
     */
    @SneakyThrows
    public static DbType getDataBaseType() {
        if (StrUtil.isNotBlank(dataSourceUrl)) {
            return JdbcUtils.getDbType(dataSourceUrl);
        }
        Environment environment = SpringContextUtils.getBean(Environment.class);
        String property = environment.getProperty("spring.datasource.url");
        if (StrUtil.isBlank(property)) {
            return DbType.MYSQL;
        }
        dataSourceUrl = property;
        return JdbcUtils.getDbType(property);
    }


    public static boolean isMySql() {
        return DbType.MYSQL == getDataBaseType();
    }

    public static boolean isOracle() {
        return DbType.ORACLE == getDataBaseType();
    }

    public static boolean isPostgerSql() {
        return DbType.POSTGRE_SQL == getDataBaseType();
    }

    public static boolean isSqlServer() {
        return DbType.SQL_SERVER == getDataBaseType();
    }


    /**
     * 兼容不同数据库的find_in_set
     *
     * @param var1 值1
     * @param var2 值2
     * @return
     */
    public static String findInSet(Object var1, String var2) {
        DbType dataBaseType = getDataBaseType();
        String var = Convert.toStr(var1);
        if (dataBaseType == DbType.SQL_SERVER) {
            // charindex(',100,' , ',0,100,101,') <> 0
            return "charindex('," + var + ",' , ','+" + var2 + "+',') <> 0";
        } else if (dataBaseType == DbType.POSTGRE_SQL) {
            // (select position(',100,' in ',0,100,101,')) <> 0
            return "(select position('," + var + ",' in ','||" + var2 + "||',')) <> 0";
        } else if (dataBaseType == DbType.ORACLE) {
            // instr(',0,100,101,' , ',100,') <> 0
            return "instr(','||" + var2 + "||',' , '," + var + ",') <> 0";
        }
        // find_in_set(100 , '0,100,101')
        return "find_in_set(" + var + " , " + var2 + ") <> 0";
    }
}
